/**
 * 
 */
package net.sf.cldsql.dj.mvc;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import net.sf.cldsql.dj.container.DiContainer;
import net.sf.cldsql.dj.container.base.DiAop;
import net.sf.cldsql.dj.db.ConnPool;
import net.sf.cldsql.dj.utl.DiException;

/**
 * ConnTransAop
 */
public class ConnTransAop implements DiAop<DiService> {
    
    private DiContainer container;
    private Connection conn;
    
    public ConnTransAop(DiContainer container) {
        this.container = container;
    }
    
    public void before(DiService delegate, Method method) {
        delegate.setContainer(container);
        delegate.setConn(conn = container.get(ConnPool.class).get());
    }
    
    public void after(DiService delegate, Method method) {
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new DiException(e);
        } finally {
            container.get(ConnPool.class).release(conn);
        }
    }
    
    public void error(DiService delegate, Method method, Exception e) {
        
        if (conn != null) {
            after(delegate, method);
        }
        throw new DiException(e);
    }
    
}
